<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="解决了精度问题，让我们再次回到我们的电机控制程序上吧。上面给出的两个例程都不是实用的程序，为什么？因为程序中存在大段的延时，而在延时的时候是什么其它的事都干不了的，想想第二个程序，整整 200 秒什么别的事都干不了，这在实际的控制系统中是绝对不允许的。那么怎么改造一下呢？当然还是用定时中断来完成了，既然每个节拍持续时间是2ms，那我们直接用定时器定时 2ms 来刷新节拍就行了。改造后的程序如下：">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="9.7、电机控制程序基础">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu062/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="解决了精度问题，让我们再次回到我们的电机控制程序上吧。上面给出的两个例程都不是实用的程序，为什么？因为程序中存在大段的延时，而在延时的时候是什么其它的事都干不了的，想想第二个程序，整整 200 秒什么别的事都干不了，这在实际的控制系统中是绝对不允许的。那么怎么改造一下呢？当然还是用定时中断来完成了，既然每个节拍持续时间是2ms，那我们直接用定时器定时 2ms 来刷新节拍就行了。改造后的程序如下：">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-27T04:53:43.752Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="9.7、电机控制程序基础">
<meta name="twitter:description" content="解决了精度问题，让我们再次回到我们的电机控制程序上吧。上面给出的两个例程都不是实用的程序，为什么？因为程序中存在大段的延时，而在延时的时候是什么其它的事都干不了的，想想第二个程序，整整 200 秒什么别的事都干不了，这在实际的控制系统中是绝对不允许的。那么怎么改造一下呢？当然还是用定时中断来完成了，既然每个节拍持续时间是2ms，那我们直接用定时器定时 2ms 来刷新节拍就行了。改造后的程序如下：">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu062/">





  <title>9.7、电机控制程序基础 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu062/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">9.7、电机控制程序基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:36:45+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>解决了精度问题，让我们再次回到我们的电机控制程序上吧。上面给出的两个例程都不是实用的程序，为什么？因为程序中存在大段的延时，而在延时的时候是什么其它的事都干不了的，想想第二个程序，整整 200 秒什么别的事都干不了，这在实际的控制系统中是绝对不允许的。那么怎么改造一下呢？当然还是用定时中断来完成了，既然每个节拍持续时间是2ms，那我们直接用定时器定时 2ms 来刷新节拍就行了。改造后的程序如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">unsigned long beats = 0; //电机转动节拍总数</span><br><span class="line">void StartMotor(unsigned long angle);</span><br><span class="line">void main()&#123;</span><br><span class="line">    EA = 1;  //使能总中断</span><br><span class="line">    TMOD = 0x01; //设置 T0 为模式 1</span><br><span class="line">    TH0 = 0xF8; //为 T0 赋初值 0xF8CD，定时 2ms</span><br><span class="line">    TL0 = 0xCD;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">    StartMotor(360*2+180); //控制电机转动 2 圈半</span><br><span class="line">    while (1);</span><br><span class="line">&#125;</span><br><span class="line">/* 步进电机启动函数，angle-需转过的角度 */</span><br><span class="line">void StartMotor(unsigned long angle)&#123;</span><br><span class="line">    //在计算前关闭中断，完成后再打开，以避免中断打断计算过程而造成错误</span><br><span class="line">    EA = 0;</span><br><span class="line">    beats = (angle * 4076) / 360; //实测为 4076 拍转动一圈</span><br><span class="line">    EA = 1;</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，用于驱动步进电机旋转 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    unsigned char tmp;  //临时变量</span><br><span class="line">    static unsigned char index = 0; //节拍输出索引</span><br><span class="line">    unsigned char code BeatCode[8] = &#123; //步进电机节拍对应的 IO 控制代码</span><br><span class="line">        0xE, 0xC, 0xD, 0x9, 0xB, 0x3, 0x7, 0x6</span><br><span class="line">    &#125;;</span><br><span class="line">    TH0 = 0xF8; //重新加载初值</span><br><span class="line">    TL0 = 0xCD;</span><br><span class="line">    //节拍数不为 0 则产生一个驱动节拍</span><br><span class="line">    if (beats != 0)&#123;</span><br><span class="line">        tmp = P1; //用 tmp 把 P1 口当前值暂存</span><br><span class="line">        tmp = tmp &amp; 0xF0; //用&amp;操作清零低 4 位</span><br><span class="line">        //用|操作把节拍代码写到低 4 位</span><br><span class="line">        tmp = tmp | BeatCode[index];</span><br><span class="line">        //把低 4 位的节拍代码和高 4 位的原值送回 P1</span><br><span class="line">        P1 = tmp;</span><br><span class="line">        index++; //节拍输出索引递增</span><br><span class="line">        index = index &amp; 0x07; //用&amp;操作实现到 8 归零</span><br><span class="line">        beats--; //总节拍数-1</span><br><span class="line">    &#125;else&#123; //节拍数为 0 则关闭电机所有的相</span><br><span class="line">        P1 = P1 | 0x0F;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序还是比较简单的，电机转动的启动函数 StartMotor 只负责计算一个需要的总节拍数beats，然后在中断函数内检测这个变量，不为 0 时就执行节拍操作，同时将其减 1，直到减到 0 为止。</p>
<p>这里，我们要特别说明一下的是 StartMotor 函数中对 EA 的两次操作。我们可以看到对beats 的赋值计算语句是夹在 EA=0;EA=1;这两行语句中间的，也就是说这行赋值计算语句在执行前先关闭了中断，而等它执行完后，才又重新打开了中断。在它执行过程中单片机是不会响应中断的，即中断函数 InterruptTimer0 不会被执行，即使这时候定时器溢出了，中断发生了，也只能等待 EA 重新置 1 后，才能得到响应，中断函数 InterruptTimer0 才会被执行。</p>
<p>那么为什么要这么做呢？我们来想一下：在本书开始我们就曾提到，我们所使用的STC89C52 单片机是 8 位单片机，这个 8 位的概念就是说单片机操作数据时都是按 8 位即按1 个字节进行的，那么要操作多个字节（不论是读还是写）就必须分多次进行了。而我们程序中定义的 beats 这个变量是 unsigned long 型，它要占用 4 个字节，那么对它的赋值最少也要分 4 次才能完成了。我们想象一下，假如在完成了其中第一个字节的赋值后，恰好中断发生了，InterruptTimer0 函数得到执行，而这个函数内可能会对 beats 进行减 1 的操作，减法就有可能发生借位，借位就会改变其它的字节，但因为此时其它的字节还没有被赋入新值，于是错误就会发生了，减 1 所得到的结果就不是预期的值了！所以要避免这种错误的发生就得先暂时关闭中断，等赋值完成后再打开中断。而如果我们使用的是 char 或 bit 型变量的话，因为它们都是在 CPU 的一次操作中就完成的，所以即使不关中断，也不会发生错误。问题分析清楚了，如何取舍还得根据实际情况来，遇上这类问题的时候多多考虑考虑吧。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu061/" rel="next" title="9.6、转动精度与深入分析">
                <i class="fa fa-chevron-left"></i> 9.6、转动精度与深入分析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2014/12/01/mcu063/" rel="prev" title="9.8、电机控制程序基础">
                9.8、电机控制程序基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
